<?php
declare(strict_types=1);

namespace app\traits;

use think\Response;

trait ResponseTrait
{
    /**
     * 成功响应
     *
     * @param mixed $data 响应数据
     * @param string $msg 响应信息
     * @param int $code 业务码
     * @return Response
     */
    protected function success($data = [], string $msg = 'success', int $code = 0): Response
    {
        return json([
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ]);
    }

    /**
     * 错误响应
     *
     * @param string $msg 错误信息
     * @param int $code 错误码
     * @param mixed $data 额外数据
     * @return Response
     */
    protected function error(string $msg = 'error', int $code = 400, $data = []): Response
    {
        return json([
            'code' => $code,
            'msg' => $msg,
            'data' => $data
        ])->code($this->getHttpCode($code));
    }

    /**
     * 分页数据响应
     *
     * @param array $list 列表数据
     * @param int $total 总记录数
     * @param int $current 当前页
     * @param int $pageSize 每页记录数
     * @param array $extra 额外数据
     * @return Response
     */
    protected function page(array $list, int $total, int $current = 1, int $pageSize = 15, array $extra = []): Response
    {
        $data = [
            'list' => $list,
            'pagination' => [
                'total' => $total,
                'current' => $current,
                'pageSize' => $pageSize,
                'pages' => ceil($total / $pageSize)
            ]
        ];

        if (!empty($extra)) {
            $data = array_merge($data, $extra);
        }

        return $this->success($data);
    }

    /**
     * 获取HTTP状态码
     *
     * @param int $code 业务码
     * @return int
     */
    protected function getHttpCode(int $code): int
    {
        $httpCodes = [
            400 => 400,  // Bad Request
            401 => 401,  // Unauthorized
            403 => 403,  // Forbidden
            404 => 404,  // Not Found
            429 => 429,  // Too Many Requests
            500 => 500   // Internal Server Error
        ];

        return $httpCodes[$code] ?? 200;
    }

    /**
     * 导出数据响应
     *
     * @param string $filename 文件名
     * @param string $content 文件内容
     * @param string $type 文件类型
     * @return Response
     */
    protected function export(string $filename, string $content, string $type = 'xlsx'): Response
    {
        return response($content, 200, [
            'Content-Type' => $this->getMimeType($type),
            'Content-Disposition' => "attachment; filename={$filename}.{$type}"
        ]);
    }

    /**
     * 获取MIME类型
     *
     * @param string $type 文件类型
     * @return string
     */
    protected function getMimeType(string $type): string
    {
        $mimeTypes = [
            'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'csv' => 'text/csv',
            'pdf' => 'application/pdf'
        ];

        return $mimeTypes[$type] ?? 'application/octet-stream';
    }
} 